import React from 'react';

/**
 * useTableReducer 参数
 */
interface TableState {
  data: any[] | Function
  pageIndex: number
  pageSize: number
  params?: Record<string, any>
  total?: number
  loading?: boolean
  isMore?: boolean
}

/**
 * 表格数据处理的几种可能类型
 */
type TableStateType = 'success' | 'error' | 'params' | 'clear' | 'init'

const initState: TableState = {
  data: [],
  params: {},
  pageIndex: 1,
  pageSize: 10,
  total: 0,
  loading: false,
  isMore: false,
};

const tableReducer: any = (
  preState: Required<TableState>,
  action: { type: TableStateType; payload: TableState },
): TableState => {
  switch (action.type) {
    case 'init':
      return {
        ...preState,
        loading: true,
      };
    case 'success':
      if (typeof action.payload.data === 'function') {
        return {
          ...preState,
          ...action.payload,
          data: action.payload.data(preState.data),
          loading: false,
        };
      }
      return {
        ...preState,
        ...action.payload,
        loading: false,
      };
    case 'params':
      if (typeof action.payload.params === 'function') {
        return {
          ...preState,
          params: action.payload.params(preState.params),
        };
      }
      return {
        ...preState,
        params: { ...preState.params, ...action.payload.params },
      };
    case 'clear':
    case 'error':
      return { ...initState, loading: false };
    default:
      return preState;
  }
};

/**
 * 表格类的数据处理
 * @param {TableState} defaultState 默认的数据
 * @returns {[TableState, React.DispatchWithoutAction | ((_p?: any) => {})]} 返回的数据
 */
export const useTableReducer = (
  defaultState?: TableState,
): [TableState, React.DispatchWithoutAction | ((_p?: any) => {})] => {
  const [state, dispatch] = React.useReducer(tableReducer, {
    ...initState,
    ...defaultState,
  });

  return [state as TableState, dispatch];
};
